import { Card, Button, Checkbox, Form, Input, message } from "antd"
import logo from '@/assets/logo.png'
import styles from './index.module.scss'
import { useDispatch } from "react-redux"
import { login } from '@/store/actions'

import { useHistory, useLocation } from "react-router-dom"
const Login = () => {
  const dispatch = useDispatch()
  const location = useLocation()
  const history = useHistory()
  const onFinish = async values => {
    try {
      await dispatch(login({ mobile: values.mobile, code: values.code }))
      message.success('登录成功', 1, () => {
        history.replace(location.state?.from || '/home')
      })
    } catch (e) {
      message.error(e.response?.data.message)
    }

  }
  return (
    <div className={styles.root}>
      <Card bodyStyle={{ padding: 20 }} className="login-wrapper" bordered={false} style={{ width: 440 }}>
        <img className="logo" src={logo}></img>
        <Form size="large" validateTrigger={['onChange', 'onBlur']} onFinish={onFinish} initialValues={{
          mobile: '13911111111',
          code: '246810',
          remeber: true
        }}>
          <Form.Item
            name='mobile'
            rules={[
              { required: true, message: '手机号为必填项' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', validateTrigger: 'onBlur' }
            ]} >
            <Input maxLength={11} />
          </Form.Item>

          <Form.Item
            name='code'
            rules={[
              { required: true, message: '验证码为必填项' },
              { len: 6, message: '验证码格式不正确', validateTrigger: 'onBlur' }
            ]} >
            <Input maxLength={6} />
          </Form.Item>

          <Form.Item
            name='remeber'
            valuePropName="checked"   >
            <Checkbox>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>

          <Form.Item >
            <Button type="primary" htmlType="submit" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
export default Login
